#!/bin/bash
function _getXPMName() {
	name="${1%.xpm}";
	name="${name/-/_}";
	name="${name/./_}";
	name="xpm$(echo "$name"|cut -c-1|tr '[:lower:]' '[:upper:]')$(echo "$name"|cut -c2-)";
	echo $name
}
function AddInclution() {
	files="";
	for a in *.xpm; do
		if [ -z "$(grep $a images.h)" ]; then
			files="$files $a";
		fi;
	done;

	if [ -n "$files" ]; then
		lines=$(cat images.h|wc -l);
		line=$(echo "$lines-2"|bc);
		hhead="$(head -$line images.h)";
		htail="$(tail -$(echo "$lines-$line"|bc) images.h)";

		echo "$hhead" >  images.h;
		for a in $files; do
			echo -n "Adding '$a' to 'images.h'... ";
			echo  >> images.h;
			echo "// Image: $(_getXPMName $a)" >> images.h;
			echo "#include <$a>" >> images.h;
			echo "Done"
		done;
		echo "$htail" >> images.h;
	fi;
}
function CleanXPM() {
	for a in *.xpm; do
		name=$(_getXPMName $a);
		sed -i "s/^static char \*.*\[/const char* const $name\[/" $a;
	done;
}
function CreateXPM() {
	for pngPath in *.png; do
		xpmPath="${pngPath%.png}.xpm";
		if [ ! -e "$xpmPath" ]; then
			name=$(_getXPMName $xpmPath);

			echo -n "Creating '$xpmPath' (name: '$name')... ";
			#pngtopnm "$pngPath" 2>/dev/null|pnmtoplainpnm 2>/dev/null|ppmtoxpm -name="$name" > "$xpmPath" 2>/dev/null;
			convert "$pngPath" "${name}.xpm";
			mv "${name}.xpm" "$xpmPath";
			echo "Done";
		fi;
	done;
}
function UpdatePRO() {
	pro="$1";
	for a in *.xpm; do
		if [ -z "$(grep $a $pro)" ]; then
			echo -n "Adding '$a' to '$pro'... ";
			echo -e "HEADERS\t\t+= images/$a" >> $pro;
			echo "Done"
		fi;
	done;
}

CreateXPM;
CleanXPM;
AddInclution;
UpdatePRO ../xados.pro;
